package com.example.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.example.entity.UserDO;
import com.example.service.UserService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @Create by Intellij IDEA
 * @Author: songXuSheng
 * @Date: 2021/9/8 9:56
 */
@RestController
@RequestMapping("/serviced")
@CrossOrigin
public class UserController {
    @Resource
    private UserService userService;
    /**
     * 查询单个用户
     * @param id 用户id
     * @return User 单个用户信息
     */
    @GetMapping("/{id}")
    public UserDO findById(@PathVariable("id") String id){
        String byId = userService.findById(id);
        UserDO userDO = JSON.parseObject(byId, UserDO.class);
        return userDO;
    }
    /**
     * 添加用户
     * @param user 用户信息
     * @return true/false
     */
    @PostMapping("/add")
    public boolean add(@RequestBody UserDO user){
        String userStr = JSON.toJSONString(user);
        Integer affectedRows = userService.addUserDO(userStr);
        if (affectedRows==1){
            return true;
        }else {
            return false;
        }
    }
    /**
     * 查询所有用户
     * @param current 当前页
     * @param limit 每页数量
     * @return Page对象
     */

    @GetMapping("/findAll/{current}/{limit}")
    public Page<UserDO> listUser(@PathVariable Long current, @PathVariable Long limit){
        String paegStr = userService.listUser(current, limit);
        return JSON.parseObject(paegStr, Page.class);
    }
    /**
     * 删除用户
     * @param id 用户ID
     * @return true/false
     */
    @ApiOperation(value = "删除用户")
    @DeleteMapping("/{id}")
    public boolean delete(@ApiParam(name = "id", value = "用户id", required = true) @PathVariable String id){
        Integer delete = userService.delete(id);
        if (delete==1){
            return true;
        }else {
            return false;
        }
    }
    /**
     * 更新用户
     * @param user 用户信息
     * @return true/false
     */
    @ApiOperation(value = "更新用户")
    @PostMapping("/update")
    public boolean update(@RequestBody UserDO user){
        String userStr = JSON.toJSONString(user);
        Integer update = userService.update(userStr);
        if (update==1){
            return true;
        }else {
            return false;
        }
    }


}
